package com.cskaoyan.order.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.order.service.OrderPromoService;
import jdk.nashorn.internal.ir.ReturnNode;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author: 杨庆
 * @since: 2022.9.29 19:56
 * @description:
 */
@Component
public class PromoConsumer {

    private DefaultMQPushConsumer consumer;
    @Autowired
    OrderPromoService promoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("create_promo_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                MessageExt messageExt = msgs.get(0);
                byte[] body = messageExt.getBody();
                String dataJson = new String(body, 0, body.length, Charset.forName("utf-8"));
                CreateSeckillOrderRequest createSeckillOrderRequest = JSON.parseObject(dataJson, CreateSeckillOrderRequest.class);
                try {

                    promoService.createPromoOrder(createSeckillOrderRequest);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.subscribe("create_promo", "*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }



    }
}
